from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
import torch

class callVLM():
    def __init__(self, local_model_path = "model/Qwen2.5-VL-3B-Instruct"):
        # 检查是否有可用的 GPU
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        print(f"using device: {self.device}")

        # 使用本地模型路径
        self.local_model_path = local_model_path  # 您的本地路径
        self.model = None
        self.processor = None

        #
        self.load_model_and_processor()

    def load_model_and_processor(self):
        # 使用本地模型
        self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
            self.local_model_path,  # 修改为本地路径
            torch_dtype="auto",
            device_map="auto"
        )
        self.processor = AutoProcessor.from_pretrained(self.local_model_path)

    def preparation(self, messages):
        text = self.processor.apply_chat_template(
            messages,
            tokenize=False,
            add_generation_prompt=True
        )
        image_inputs, video_inputs = process_vision_info(messages)
        inputs = self.processor(
            text=[text],
            images=image_inputs,
            videos=video_inputs,
            padding=True,
            return_tensors="pt",
        )
        inputs = inputs.to(self.device)  # 使用动态设备
        return inputs

    def get_response(self, messages):
        inputs = self.preparation(messages)

        generated_ids = self.model.generate(**inputs, max_new_tokens=128)
        generated_ids_trimmed = [
            out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
        ]
        output_text = self.processor.batch_decode(
            generated_ids_trimmed,
            skip_special_tokens=True,
            clean_up_tokenization_spaces=False
        )
        return output_text
